package cn.mesmile.shiro.config;

import cn.hutool.core.util.StrUtil;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * @author zb
 * @date 2021/2/7 19:04
 * @Description:
 * * SessionManager
 *
 *        DefaultSessionManager： 默认实现，常用于javase
 *        ServletContainerSessionManager: web环境
 *        DefaultWebSessionManager：常用于自定义实现
 */
public class CustomSessionManager extends DefaultWebSessionManager {

    /**
     *  自定义：前端请求传递过滤的请求头名称
     */
    private static final String AUTHORIZATION = "token";

    public CustomSessionManager(){
        super();
    }

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {

        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        // 自定义请求头
        String sessionId = httpServletRequest.getHeader(AUTHORIZATION);

        if(StrUtil.isNotEmpty(sessionId)){

            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, ShiroHttpServletRequest.COOKIE_SESSION_ID_SOURCE);

            //在此处自动将其标记为有效。如果无效，则
            //下面的onUnknownSession方法将被调用，届时我们将删除该属性。
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);

            return sessionId;
        }else {
            // 从 cokie 中获取  JSESSIONID
//            return super.getSessionId(request, response);
            // 禁止从cookie 中获取
            return sessionId;
        }
    }
}
